import axios from 'axios'
import { ElMessage } from 'element-plus'
import {useRouter} from '@/router'
import db from '@/utils/localstorage'

const router = useRouter()
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL || '/api',
  timeout: 5000 
})
service.interceptors.request.use(config => {
  config.headers["Authorization"] = localStorage.getItem('token') || ''
  config.headers["Tenant"] = "pico";
  return config;
},error => {
  return Promise.reject(error);
})
service.interceptors.response.use(response => {
  const {data} = response
  if (data.code === 0 ){
    // 
  } else if (data.code == 600603) {
    ElMessage.error(data.msg)
    db.clear()
    router.replace("/login")
    location.reload()
  } else {
    ElMessage.error(data.msg)
  }
  return data
}, error => {
  error.response && ElMessage.error(error.response?.data)
  return Promise.reject(new Error(error.response?.data||error))
})
export default service